import { useDispatch, useSelector } from 'react-redux';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import {router} from './router/index.tsx';
import { generatesRouters } from './util/generatesRoutes.tsx';
import {useEffect, useState } from 'react';
import { menu } from './api/users.ts';
import { setMenuList } from './store/modules/userStore.ts';
export default function App() {
  const dispatch=useDispatch()
  const {menuList,token}=useSelector((state:any)=>state.userReducer)
  const [route,setRoute]=useState<any>(null)
  useEffect(()=>{
    /* 
      router: 基本静态路由
      routes：通过路由对照表与menulist获取的动态路由
      router[0].children 静态home组件的子路由
    */
    async function getMenuList(){
      const res=await menu()
      if(res.data.data.length){
        dispatch(setMenuList(res.data.data)) // 更新Redux状态
        // 直接使用API返回的数据生成路由，而不是使用Redux中的menuList
        const routes=generatesRouters(res.data.data)
        router[0].children=routes
        // 添加安全检查，确保children数组不为空
        if(router[0].children && router[0].children.length > 0){
          router[0].children[0].index=true
        }
        const myRouter=createBrowserRouter(router)
        setRoute(myRouter)
      }else{
        const basicRouter=createBrowserRouter(router)
        setRoute(basicRouter)
      }
    }
    //防止组件刷新初始化之后menuList获取的时序问题 在App中重新获取menuList 可以将sider中的异步优化掉了
    getMenuList()//如果获取失败就会阻塞后续的操作 所以可以省略后续的判断
  },[token])

  if(route){
    return (
    <div className='App'>
        <RouterProvider router={route}></RouterProvider>
    </div>
  )
  }else{
    return(
      <div>
        Loading...
      </div>
    )
  }
}